<template>
  <div>
    <Row v-show="!showDeviceDetailView">
      <Row class="list_row" style="margin-top: 0px;min-height: 400px;">
        <Row style="margin: 5px 0px 10px 0px;">
          <Select v-model="selTrainCenterId" filterable   :placeholder="$t('common.trainSePlaceTips')" style="width: 200px;margin-right: 20px"
                  v-show="isCanChooseTc">
            <Option v-for="tc in trainCenterList" :value="tc.id" :key="tc.id">{{tc.name}}</Option>
          </Select>
          <Input v-model="searchKeyword" :placeholder="$t('deviceP.phoneOrStudentTips')" style="width: 200px;margin-right: 20px"/>
          <Button  class="btnWhite"  icon="ios-search" style="margin-right: 20px" @click="search">{{$t('search')}}</Button>
          <Button  class="btnWhite"  icon="md-add" @click="showAddModal">{{$t('trainerP.inviteCoacheBtn')}}</Button>
        </Row>
        <Table :columns="coachColumn" border :data="dataList" stripe :no-data-text="noDataMsg">
          <template slot-scope="{ row, index }" slot="seq">
            {{(currentPage - 1) * pageSize + index + 1}}
          </template>
          <template slot-scope="{ row, index }" slot="status">
            <Icon v-if="row.status == 0" custom="iconfont icon-device" size="24" color="#aaaaaa"/>
            <Icon v-else custom="iconfont icon-device" size="24" color="#2d8cf0"/>
          </template>
        </Table>
        <div class="div_page">
          <Page :total="totalCount" :current="currentPage" :page-size="pageSize"
                show-total show-elevator prev-text="<" next-text=">" @on-change="pageChg"/>
        </div>
      </Row>
    </Row>

    <!-- 邀请教练弹窗 -->
    <Modal v-model="entityModelVisiable" :mask-closable="false" width="700" :title="$t('trainerP.inviteCoacheBtn')">
      <Row class="list_row" style="margin-top: 0px">
        <Row style="margin: 5px 0px 10px 0px;">
          <Input v-model="searchCoachKeyword"  :placeholder="$t('deviceP.phoneOrStudentTips')" style="width: 200px;margin-right: 20px"/>
          <Button type="primary" icon="ios-search" style="margin-right: 20px" @click="searchNonJoinedCoach">{{$t('search')}}</Button>
        </Row>
        <Table :columns="inviteCoachColumn" border :data="inviteCoachList" stripe style="min-height: 278px;">
          <template slot-scope="{ row, index }" slot="seq">
            {{(currentPage - 1) * pageSize + index + 1}}
          </template>
        </Table>
        <div class="div_page">
          <Page :total="coachTotalCount" :current="coachCurrentPage" :page-size="coachPageSIze"
                show-total show-elevator prev-text="<" next-text=">" @on-change="coachPageChg"/>
        </div>
      </Row>
      <div slot="footer" style="text-align: center">
        <Button @click="cancelInviteCoach">{{$t('cancel')}}</Button>
      </div>
      <div slot="close" style="text-align: center">
        <i class="ivu-icon ivu-icon-ios-close" @click="cancelInviteCoach" ></i>
      </div>
    </Modal>

    <!-- 选择学员弹窗 -->
    <Modal v-model="assignTrainerModelVisiable" :mask-closable="false" width="650" :title="$t('trainerP.assignTraineeBtn')">
      <div>
        <Transfer ref="myTransfer"
                  style="margin: 0px 10px"
                  :list-style="listStyle"
                  :data="allTrainerList"
                  :titles="[this.$t('trainerP.traineeList'), this.$t('trainerP.assignedTrainee')]"
                  filterable
                  :filter-method="filterTrainer"
                  :target-keys="selTrainerIds"
                  :render-format="transferRender"
                  @on-change="transferOnChange"></Transfer>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="cancelAssignTrainer">{{$t('cancel')}}</Button>
        <Button type="primary" @click="saveassignTrainer" :loading="saveLoading" style="margin-left: 15px">
          <span v-if="!saveLoading">{{$t('save')}}</span>
          <span v-else>{{$t('save')}}....</span>
        </Button>
      </div>
      <div slot="close" style="text-align: center">
        <i class="ivu-icon ivu-icon-ios-close" @click="cancelAssignTrainer" ></i>
      </div>
    </Modal>
      <!-- 教练详细信息 -->

    <Modal v-model="coachInfoVisible" :mask-closable="false" width="660" :title="$t('trainerP.coachInfoBtn')">
      <div class="detail_div">
        <Row>
          <Col span="4" class="form_filed">{{$t('cocach')}}:</Col>
          <Col span="8" class="form_filed_val"><span class="wrapBox">{{  coachInfo.nickName }}</span></Col>
          <Col span="4" class="form_filed">{{$i18n.locale === 'zh-CN' ? $t('common.phone') :  $t('common.mail')  }}:</Col>
          <Col span="8" class="form_filed_val"><span class="wrapBox">{{ $i18n.locale === 'zh-CN' ?  coachInfo.phone : coachInfo.mail }}</span></Col>
        </Row>

        <Row>
          <Col span="4" class="form_filed">{{$t('common.gender')}}:</Col>
          <Col span="8" class="form_filed_val">
          <span  class="wrapBox" v-if=" coachInfo.sex == 1">{{$t('common.male')}}</span>
          <span  class="wrapBox" v-if=" coachInfo.sex == 2">{{$t('common.female')}}</span>
          </Col>
          <Col span="4" class="form_filed">{{$t('common.birthday')}}:</Col>
          <Col span="8" class="form_filed_val"><span class="wrapBox">{{  coachInfo.birthday }}</span></Col>
        </Row>
         <Row>
          <Col span="4" class="form_filed">{{$t('trainerP.venue')}}:</Col>
          <Col span="8" class="form_filed_val"><span class="wrapBox">{{  coachInfo.trainCenterName }}</span></Col>
          <!-- <Col span="4" class="form_filed">运动队名称:</Col>
          <Col span="8" class="form_filed_val">{{  coachInfo.sportsTeamName }}</Col> -->
          <Col span="4" class="form_filed">{{$t('trainerP.coacheLevel')}}:
          </Col>
          <Col span="8" class="form_filed_val">
            <Select v-model="coachInfo.level" :placeholder="$t('trainerP.coachSelplaceTips')" style="width:100%;" @on-change="changeLevelHandle">
          <Option v-for="tc in levelList" :value="tc.val" :key="tc.val">{{tc.label}}</Option>
        </Select>
          </Col>
        </Row>

       <Row>

          <Col span="4" class="form_filed">{{$t('common.facePhotoUrl')}} :</Col>
          <Col span="8" class="form_filed_val"><img style="width:67px; height: 55px;"
           :src= coachInfo.facePhoto /></Col>

          <!-- <Col span="4" class="form_filed">教练等级:
          </Col>
          <Col span="8" class="form_filed_val"><span class="wrapBox">{{  coachInfo.level }}</span></Col> -->

        </Row>
      </div>
      <div slot="footer" style="text-align: center">
        <Button @click="coachInfoVisible = false">{{$t('cancel')}}</Button>
      </div>

    </Modal>

  </div>
</template>
<script>
import TrainCenterApi from '@/api/trainCenterApi'
import CoachApi from '@/api/coachApi'
import { isEmpty } from '@/libs/util'
import UserApi from "@/api/userApi";
export default {
  data () {
    return {
      coachInfo: {level:''},
      coachInfoVisible: false,
      inviteCoachList: [],
      coachPageSIze: 5,
      coachCurrentPage: 1,
      coachTotalCount: 0,
      searchCoachKeyword: '',
      assignTrainerModelVisiable: false,
      coachList: [],
      allTrainerList: [],
      selTrainerIds: [], // 当前教练分配的学员
      selCoachId: '', // 当前选中的教练
      saveLoading: false,
      searchKeyword: '',
      noDataMsg:this.$t('common.noData'),
      isCanChooseTc: false,
      selTrainCenterId: '',
      trainCenterList: [],
      showDeviceDetailView: false,
      entityModelVisiable: false,
      totalCount: 20,
      currentPage: 1,
      pageSize: 10,
      dataList: [],
      listStyle:{
       width:'250px'
      },
      levelList:[
      {
        val:'',
        label:''
      },
      {
        val:'1',
        label:this.$t('trainerP.primary'),
      },
      {
        val:'2',
        label:this.$t('trainerP.intermediate'),
      },
      {
        val:'3',
        label:this.$t('trainerP.senior'),
      },
    ],
      inviteCoachColumn: [
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          title: this.$t('common.avatar'), 
          key: 'avatar',
          render: (h, params) => {
            // return h('strong', params.row.avatar)
            if (!params.row.avatar) {
              return h("div", {
                    class: "avatorBox",
                  },
            )
            }
            return h('img', {
              style: { // 样式
                'width': '20px',
                'border': '1px solid'
              },
              attrs: {
                src: params.row.avatar
              },
              on: {
                click: () => { this.showBigImg(params.row.avatar) }
              }

            })
          }
        },
        {
          title: this.$t('cocach'), 
          key: 'nickName'
        },
        {
          title: this.$i18n.locale === 'zh-CN' ? this.$t('common.phone') : this.$t('common.mail'), 
          key: this.$i18n.locale === 'zh-CN' ? "phone" : "mail",
        },
        {
          title:this.$t('common.optColumn'),
          key: 'action',
          width: 180,
          render: (h, params) => {
            return h('div', [
              h('span', {
                props: {
                
                  size: 'small'
                },
                style: {
                  marginRight: "15px",
                    background: "#484a52",
                    padding: " 5px 10px",
                    color: "#fff",
                    display: "inline-block",
                    borderRadius: "5px",
                    cursor: "pointer",
                },
                on: {
                  click: () => {
                    this.inviteTrainer(params.row)
                  }
                }
              }, this.$t('trainerP.joinBtn'))
            ])
          }
        }
      ],
      coachColumn: [
        {
          title: this.$t('common.seq'), 
          slot: "seq",
          width: '110',
          render: (h, params) => {
            return h('span', {
              class: 'sortBlock'
            }, params.index + 1)
          }
        },
        {
          title: this.$t('common.avatar'), 
          key: 'avatar',
          render: (h, params) => {
            // return h('strong', params.row.avatar)
            if (!params.row.avatar) {
              return h("div", {
                    class: "avatorBox",
                  },
            )
            }
            return h('img', {
              style: { // 样式
                'width': '20px',
                'border': '1px solid'
              },
              attrs: {
                src: params.row.avatar
              },
              on: {
                click: () => { this.showBigImg(params.row.avatar) }
              }

            })
          }
        },
        {
          title: this.$t('cocach'), 
          key: 'nickName'
        },
        {
          title: this.$i18n.locale === 'zh-CN' ? this.$t('common.phone') : this.$t('common.mail'), 
          key: this.$i18n.locale === 'zh-CN' ? "phone" : "mail",
        },
        {
          
          title: this.$t('trainerP.trainerCount'), 
          key: 'trainerCount'
        },
        {
          title: this.$t('trainerP.createTime'),
          key: 'createTime'
        },
        {
          title:this.$t('common.optColumn'),
          key: 'action',
          width: '350',
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'btnBlue',
                on: {
                  click: () => {
                    this.showCachInfo(params.row)
                  }
                }
              }, this.$t('trainerP.coachInfoBtn') ),
              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                style: {
                  marginRight: '15px'
                },
                class: 'btnYellow',
                on: {
                  click: () => {
                    this.showAssignModal(params.row)
                  }
                }
              }, this.$t('trainerP.assignTraineeBtn') ),

              h('Button', {
                props: {
                  type: 'error',
                  size: 'small'
                },
                class: 'btnRed',
                on: {
                  click: () => {
                    this.del(params.row)
                  }
                }
              },  this.$t('trainerP.unbindBtn'))
            ])
          }
        }]
    }
  },
  watch: {
    'selTrainCenterId': function (val) {
      this.initTrainerList()
    },

  },
  created () {
    this.initFunc()
  },
  methods: {
    changeLevelHandle(v){
      
      this.coachInfo.level=v
      this.updateLevel()
    },
    updateLevel(){
      
      UserApi.levelPeople(this.coachInfo.id,this.coachInfo.level).then( (res) => {
        
        // if(res.data.code ==200){
        //   this.$Message.success('更新成功！')
        // }
         
        },
        (error) => {
          this.$Message.error(error.response.data.msg);
        })
    },
    showCachInfo (row) {
      CoachApi.detail(row.id).then(res => {
        this.coachInfoVisible = true
        this.coachInfo = res.data.data
      })
    },
    // 重置邀请教练的查询
    cancelInviteCoach () {
      this.searchCoachKeyword = ''
      this.entityModelVisiable = false
    },
    // 重置分配学员的查询
    cancelAssignTrainer () {
      this.assignTrainerModelVisiable = false
      if (this.$refs.myTransfer) {
        this.$refs.myTransfer.$children['0']._data.query = ''
        // 清空右边搜索
        this.$refs.myTransfer.$children['2']._data.query = ''
      }
    },
    // 初始化所选训练中心的所有学员（后续为教练分配学员需要该列表）
    initTrainerList () {
      TrainCenterApi.queryTrainCenterTrainers(this.selTrainCenterId).then(res => {
        const data = res.data.data
        for (var i = 0; i < data.trainers.length; i++) {
          var coach = data.trainers[i]
          coach['key'] = coach.id
        }
        this.allTrainerList = data.trainers
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    initFunc () {
      TrainCenterApi.userTrainCenterScope().then(res => {
        const data = res.data.data
        if (data.canSelect == '1') {
          this.isCanChooseTc = true
          this.trainCenterList = data.list
          if (this.trainCenterList.length > 0) {
            this.selTrainCenterId = this.trainCenterList[0].id
          }
        } else {
          this.selTrainCenterId = data.trainCenterId
        }
        this.search()
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    search () {
      this.currentPage = 1
      this.fetchDataList()
    },
    fetchDataList () {
      if (isEmpty(this.selTrainCenterId)) {
        this.$Message.error(this.$t('common.trainSePlaceTips'));
        return
      }
      this.noDataMsg = this.$t('common.loading');
      this.dataList = []
      var param = { 'pageSize': this.pageSize, 'currentPage': this.currentPage, 'trainCenterId': this.selTrainCenterId }
      if (this.searchKeyword.length > 0) {
        param.nickName = this.searchKeyword
      }
      CoachApi.pageResult(param).then(res => {
        this.dataList = res.data.data.pageResult.items
        this.totalCount = res.data.data.pageResult.totalCount
        this.noDataMsg = this.$t('common.noData')
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    pageChg (selPage) {
      this.currentPage = selPage
      this.fetchDataList()
    },
    del (row) {
      this.$Modal.confirm({
        title:this.$t('trainerP.unbindPromot'),
        content:this.$t('trainerP.unbindCt'),
        okText: this.$t('trainerP.unbindBtn'),
        cancelText:  this.$t('cancel'),
        onOk: () => {
          this.doDel(row.id)
        }
      })
    },
    doDel (coachId) {
      this.$Spin.show()
      CoachApi.unbind(this.selTrainCenterId, coachId).then(res => {
        this.$Spin.hide()
        this.$Message.success(this.$t('common.unBindSuc'))
        this.fetchDataList()
      }, error => {
        this.$Spin.hide()
        this.$Message.error(error.response.data.msg)
      })
    },
    transferRender (coach) {
      if(!coach.avatar){
        if(this.$i18n.locale === 'zh-CN'){
          return `<div class="tranBox"><div class="avatorBox"></div> ${coach.nickName}  ( ${coach.phone} )</div>`
        }else{
          return `<div class="tranBox"><div class="avatorBox"></div> ${coach.nickName}  ( ${coach.mail} )</div>`
        }
      }else{
        if(this.$i18n.locale === 'zh-CN'){
          return `<div class="tranBox"> <img src="${coach.avatar}" style="width:20px;height:20px;" /> ${coach.nickName}  ( ${coach.phone} )</div>`
        }else{
          return `<div class="tranBox"> <img src="${coach.avatar}" style="width:20px;height:20px;" /> ${coach.nickName}  ( ${coach.mail} )</div>`
        }
      }
      
    },
    transferOnChange (newTargetKeys, direction, moveKeys) {
      this.selTrainerIds = newTargetKeys
    },
    filterTrainer (data, query) {
      // console.log("data:" + JSON.stringify(data))
      var name = data.nickName
      if (isEmpty(name)) {
        name = ''
      }
      if(this.$i18n.locale === 'zh-CN'){
        return name.indexOf(query) > -1 || data.phone.indexOf(query) > -1
      }else{
        return name.indexOf(query) > -1 || data.mail.indexOf(query) > -1
      }

    },
    showAssignModal (row) {
      this.assignTrainerModelVisiable = true
      this.selTrainerIds = row.trainerIdList
      this.selCoachId = row.id
    },
    saveassignTrainer () {
      if (this.selTrainerIds.length == 0) {
        this.$Modal.confirm({
          title: this.$t('trainerP.traineeAssignTitleConfirm'),
          content:this.$t('trainerP.assignTisTextTrain') ,
          okText:  this.$t('yes'),
          cancelText: this.$t('cancel'),
          onOk: () => {
            this.doAssign()
          }
        })
      } else {
        this.doAssign()
      }
    },
    doAssign () {
      this.saveLoading = true
      const trainerIds = this.selTrainerIds.join(',')
      CoachApi.updateCoachTrainer(this.selTrainCenterId, this.selCoachId, trainerIds).then(res => {
        this.saveLoading = false
        this.assignTrainerModelVisiable = false
        this.$Message.success(this.$t('trainerP.assignSuc'));
        this.fetchDataList()
      }, error => {
        this.saveLoading = false
        this.$Message.error(error.response.data.msg)
      })
    },
    showAddModal () {
      this.entityModelVisiable = true
      this.searchNonJoinedCoach()
    },

    coachPageChg (selPage) {
      this.coachCurrentPage = selPage
      this.searchNonJoinedCoach()
    },
    // 查询未加入的教练列表
    searchNonJoinedCoach () {
    
      var param = { 'currentPage': this.coachCurrentPage, 'trainCenterId': this.selTrainCenterId, 'pageSize':this.coachPageSIze }
      if (this.searchCoachKeyword.length > 0) {
        param.searchKeyword = this.searchCoachKeyword
      }
      CoachApi.searchNotJoinedTrainers(param).then(res => {
        this.inviteCoachList = res.data.data.pageResult.items
        this.coachTotalCount = res.data.data.pageResult.totalCount
      }, error => {
        this.$Message.error(error.response.data.msg)
      })
    },
    inviteTrainer (row) {
      this.$Modal.confirm({
        title:this.$t('trainerP.inviteTitleConfirm'),
        content:  this.$i18n.locale === "zh-CN" ? "确认邀请教练：【" + row.nickName + "】加入吗?" : "Are you sure to invite coaches [" + row.nickName +"] to join?",
        okText: this.$t('trainerP.inviteBtn'),
        cancelText:  this.$t('cancel'),
        onOk: () => {
          this.doInvite(row.id)
        }
      })
    },
    doInvite (trainerId) {
      this.$Spin.show()
      CoachApi.invite(this.selTrainCenterId, trainerId).then(res => {
        this.$Spin.hide()
        this.entityModelVisiable = false
        this.$Message.success(this.$t("trainerP.iniviteSuc"));
      }, error => {
        this.$Message.error(error.response.data.msg)
        this.$Spin.hide()
      })
    }
  }
}
</script>
<style>

.avatorBox{
  background:url('../../assets/images/icon_tx_boy.png');
  background-size:contain;
  width:20px;
  height:20px;
  margin:5px;
  margin-left:0
}
.wrapBox{
  border:1px solid #dcdee2;
  border-radius: 4px;
    color: #515a6e;
    background-color: #fff;
    display: inline-block;
    width: 100%;
    min-height: 32px;
    line-height: 1.5;
    padding: 4px 7px;
}
.tranBox{
  font-size:12px;
  display:flex;
  align-items:center;
}
.ivu-transfer-list-content-item{
  display:flex;
  
}
</style>
